<template>
  <div class="app-container">
    <el-card class="box-card" shadow="never" >
    <div class="filter-container">
      <el-input placeholder="分类名称" class="filter-item search-item"
                v-model="queryParams.model.name"/>

      <el-button @click="handleQuery" class="filter-item" plain type="primary">{{ $t('table.search') }}</el-button>
      <el-button @click="reset" class="filter-item" plain type="warning">{{ $t('table.reset') }}</el-button>
      <el-button @click="handleCreate" class="filter-item" plain type="danger" v-has-permission="['authority:application:add']">
        {{ $t("table.add") }}
      </el-button>

    </div>
      <el-table
        :data="tableData.records"
        :key="tableKey"
        @cell-click="cellClick"
        @filter-change="filterChange"
        @selection-change="onSelectChange"
        @sort-change="sortChange"
        border fit row-key="id"
        ref="table"
        style="width: 100%;"
        v-loading="loading"
      >
        <el-table-column label="名称" :show-overflow-tooltip="true" sortable="name" align="left"
                         min-width="120px" prop="name">
          <template slot-scope="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建者" :show-overflow-tooltip="true" sortable="createName"  align="left"
                         min-width="120px" prop="createName">
          <template slot-scope="scope">
            <span>{{ scope.row.createName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" :show-overflow-tooltip="true" sortable="createTime"  align="left"
                         min-width="120px" prop="createTime">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.operation')" align="center" column-key="operation"
                         class-name="small-padding fixed-width" fixed="right" width="110px">
          <template slot-scope="{row}">
            <i @click="handleEdit(row)" class="el-icon-edit table-operation" style="color: #2db7f5;"
               v-has-permission="['authority:application:edit']"></i>
            <i @click="handleDelete(row)" class="el-icon-delete table-operation" style="color: #f50;"
               v-has-permission="['authority:application:delete']"></i>
          </template>
        </el-table-column>

      </el-table>

      <pagination
        :limit.sync="queryParams.size"
        :page.sync="queryParams.current" :total="Number(tableData.total)"
        @pagination="fetch" v-show="tableData.total>0"/>


      <el-dialog :title="dialogFormVisibleName===1?'新建分类':'编辑分类'" :visible.sync="open" width="600px">
        <div class="tpl-create-content">
          <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px">
            <el-form-item label="分类名称" prop="name" style="width: 95%">
              <el-input v-model="ruleForm.name" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer" style="text-align: right">
            <el-button type="primary" @click="dialogFormVisibleName===1?submitForm('ruleForm'):editForm('ruleForm')">提交</el-button>
            <el-button @click="open = false">取 消</el-button>
          </div>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import classifyApi from '@/api/process/admin/classify.js'
import Pagination from '@/components/Pagination'
import elDragDialog from '@/directive/el-drag-dialog'
import {downloadFile, initQueryParams} from '@/utils/commons'
export default {
  name: 'Classify',
  directives: {elDragDialog},
  components: {Pagination},
  data() {
    return {
      dialogFormVisibleName: 1,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 是否显示弹出层
      open: false,

      queryParams: initQueryParams({
        model: {}
      }),
      selection: [],
      tableKey: 0,
      tableData: {
        total: 0
      },
      ruleForm: {
        id: undefined,
        name: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入流程分类', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetch()
  },
  methods: {
    fetch(params = {}) {
      this.loading = true;
      if (this.queryParams.timeRange) {
        this.queryParams.extra.createTime_st = this.queryParams.timeRange[0];
        this.queryParams.extra.createTime_ed = this.queryParams.timeRange[1];
      }
      this.queryParams.current = params.current ? params.current : this.queryParams.current;
      this.queryParams.size = params.size ? params.size : this.queryParams.size;
      classifyApi.page(this.queryParams).then(response => {
        console.log("\"查询\"",response.data.data.records)
        const res = response.data;
        if (res.isSuccess) {
          this.tableData = res.data;
        }
        this.loading = false
      }).finally(() => this.loading = false);
    },
    handleCreate() {
      this.ruleForm = {
        id: undefined,
        name: ''
      }
      this.dialogFormVisibleName = 1
      this.open = true
    },
    handleEdit(row) {
      this.dialogFormVisibleName = 2
      this.ruleForm.id = row.id
      this.ruleForm.name = row.name
      this.open = true
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          classifyApi.createClassify(this.ruleForm).then(response => {
            if (response !== undefined) {
              this.fetch()
              this.$message({
                type: 'success',
                message: '分类已增加!'
              })
              this.open = false
            }
          })
        }
      })
    },
    editForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          classifyApi.updateClassify(this.ruleForm).then(response => {
            if (response !== undefined) {
              this.fetch()
              this.$message({
                type: 'success',
                message: '分类已更新!'
              })
              this.open = false
            }
          })
        }
      })
    },
    handleQuery() {
      this.queryParams.pageIndex = 1
      this.queryParams.pageSize = 10
      this.fetch()
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        classifyApi.deleteClassify({
          id: row.id
        }).then(response => {
          if (response !== undefined) {
            this.fetch()
            this.$message({
              type: 'success',
              message: '分类已删除!'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleSelectionChange() {},
    closeDrawer(done) {
      done()
      this.currentRow = {}
    },
    search() {
      this.fetch({
        ...this.queryParams,
      })
    },
    reset() {
      this.queryParams = initQueryParams({
        model: {}
      });
      this.$refs.table.clearSort()
      this.$refs.table.clearFilter()
      this.search()
    },
    sortChange(val) {
      this.queryParams.sort = val.prop;
      this.queryParams.order = val.order;
      if (this.queryParams.sort) {
        this.search();
      }
    },
    filterChange(filters) {
      for (const key in filters) {
        if (key.includes('.')) {
          const val = {};
          val[key.split('.')[1]] = filters[key][0];
          this.queryParams.model[key.split('.')[0]] = val;
        } else {
          this.queryParams.model[key] = filters[key][0]
        }
      }
      this.search()
    },
    onSelectChange(selection) {
      this.selection = selection
    },
    cellClick(row, column) {
      if (column['columnKey'] === "operation") {
        return;
      }
      if (column['columnKey'] === "clientId") {
        copy(row[column.property]);
        this.$message({
          message: this.$t('tips.copySelected'),
          type: 'success'
        })
        return;
      }

      let flag = false;
      this.selection.forEach((item) => {
        if (item.id === row.id) {
          flag = true;
          this.$refs.table.toggleRowSelection(row);
        }
      })
      if (!flag) {
        this.$refs.table.toggleRowSelection(row, true);
      }
    },
  }
}
</script>
